<template>
  <div class="content">
    <div class="message_title">
      <ul style="list-style: none">
        <li class="ali"><div> <img src="../assets/images/internet.png"  width="40" height="40" alt="" /> </div></li>
        <li class="bli"><div style="width: 200px; height:20px; color: white;font-weight: bolder;font-size: x-large">分布式聊天室</div></li>
        <li class="dli"><div style="width: 500px; height:20px; color: white;font-weight: bolder;font-size: large">
          <div style="float:left;margin-top: -13px;margin-left: 55%"><img :src="computedImageSrc" width="50" height="50" alt="" /></div>
          <div style="float: right;margin-right: 10px;margin-top: -16px;line-height: 18px ;font-size:10px;text-align: left;color: #cccccc">
            <span style="display: block; font-size:small;color: white">昵称账号：{{ NICK_NAME}}</span>
            <span style="display: block">登录时间：{{currentTime}}</span>
            <span style="display: block">地区：{{currentLocal.latitude}} {{currentLocal.longitude}} </span>
          </div>
        </div>
        </li>
        <li class="cli">
          <div style="cursor: pointer; text-align: center;vertical-align: center; width: 180px; height:30px; background-color: rgba(96, 173, 207, 0.9); font-weight: bolder;font-size: large;color: white">
            <span style="margin-top: 20px" @click="offLine" >离开房间</span>
        </div>
        </li>
      </ul>

    </div>
    <div class="room_content">
      <div class="room_01">
        <div style="margin-top:30px;margin-left: 10px"><img src="../assets/images/room.png" width="50" height="50"></div>
        <div style="margin-top: -45px;    margin-left: 85px; font-size: x-large">房间号</div>
        <div style="margin-top: 30px ;background-color: rgba(96, 173, 207, 0.9); line-height:40px;text-align: center ">{{ CHAT_ROOM_ID}}</div>
      </div>

      <div class="romm_02">
        <div style="margin-left: 10px"><img src="../assets/images/onine.png" width="50" height="50"></div>
        <div style="margin-left: 85px; margin-top:-45px; font-size: x-large">在线用户</div>
        <div style="margin-top: 20px; margin-left:50px ">
          <ul
            v-for="(item, index) in onlineUsers"
            :key="chat"
          >

            <li> {{item.nickName}} </li>

          </ul>
        </div>

      </div>

    </div>
    <div class="message_content">
      <!-- 消息区 -->
      <div class="message_area" ref="chatWindow">
        <ul
          class="message_item"
          :style="{
            justifyContent: item.from === NICK_NAME ? 'flex-end' : 'flex-start',
          }"
          v-for="(item, index) in messageList"
          :key="chat"
        >

<!--      系统消息    -->

          <li  v-if=" item.msgType === '20' || item.msgType === '30' ">

            <ul>
              <li style="margin-left:-15px">
                <p class="avator_left"  >
                   <img src="../assets/head/sys.png" style="width: 40px;height: 40px" alt="" />
                </p>
                <div  class="name_left">{{ item.from }}
                  <span style="color: #5a5e66; font-size:small">&nbsp;{{ item.sendTime }}</span></div>

              </li>

              <li style="margin-left:-15px; ">
                <p class="message message_left">  {{ item.content }} </p>
              </li>
            </ul>

          </li>

<!-- 当前房间内所用的消息  -->
            <li  v-if=" item.msgType === '10' && item.from !== NICK_NAME  && item.channel  === CHAT_ROOM_ID ">

              <ul>
                <li style="margin-left:-15px">
                  <p class="avator_left"  >
                  <img v-if="item.msgType === '10'" :src="computedTaImageSrc" style="width: 40px;height: 40px" alt="" />
                </p>
                  <div  class="name_left">{{ item.from }}
                    <span style="color: #5a5e66; font-size:small">&nbsp;{{ item.sendTime }}</span></div>

                </li>
                <li style="margin-left:-15px; ">
                  <p class="message message_left">  {{ item.content }} </p>
                </li>
              </ul>

            </li>

<!--    我的消息      -->

            <li style="margin-top: 10px" v-if=" item.msgType === '10' && item.from == NICK_NAME && item.channel ===  CHAT_ROOM_ID" >
              <ul>
                <li style="    float: right;    margin-top: -70px;    margin-right: 20px;">
                  <p class="avator_right" >
                  <img :src="computedImageSrc" style="width: 40px;height: 40px" alt="" />
                </p>
                 </li>
                <li style="margin-top: 45px">
                  <p class="message message_right">
                    {{ item.content }}
                  </p>
                </li>
              </ul>

            </li>

        </ul>
      </div>
    </div>
    <div class="message_face">
      <el-popover
        placement="bottom"
        title="选择表情"
        width="500"
        height="700"
        trigger="click"
        v-model="emojiShow"
      >
        <el-button slot="reference">😀</el-button>
        <div class="faceBox">
          <ul>
            <li
              v-for="(item, index) in faceList"
              :key="index"
              @click="getEmojis(index)"
            >
              {{ item }}
            </li>
          </ul>
        </div>
      </el-popover>
    </div>
    <div class="message_input">

       <el-input
        type="textarea"
        style=" width:90%;height: 65px !important;  color: #fff;   min-height: 105px !important;    /* background-color: transparent; */   border: 0;"
        v-model="textarea"
        autofocus
        :autosize="{ minRows: 2, maxRows: 5 }"
        resize="none"
        @keyup.enter="keyDown($event)"
      >
      </el-input>
      <div
        style="

            width: 18%;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            height: 50px;
            margin-top: -13.4%;
    margin-left: 100%;
    background-color: rgba(96, 173, 207, 0.9);
          "
      >
        <img src="../assets/images/send.png" width="40" height="40" style="color: white"></img>
        <el-button @click="send" >发送</el-button>
      </div>

      <!-- 添加或修改岗位对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="300px" append-to-body>
        <el-form ref="form" :model="form"   label-width="80px">
          <el-form-item label="聊天方式" prop="chatType">
            <el-radio-group v-model="form.chatType">
              <el-radio key="10" label="10" >单聊</el-radio>
              <el-radio key="20" label="20" >群聊</el-radio>
            </el-radio-group>
          </el-form-item>
         </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


      <el-dialog :title="onlineTitle" :visible.sync="onlineOpen" width="400px" append-to-body>
        <el-form ref="form2" :model="form2"   label-width="80px">
          <el-form-item label="在线用户" prop="chatType">
            <el-radio-group v-model="form2.onlineUser">
              <el-radio
                v-for="dict in onlineRadioUsers"
                :key="dict.nickName"
                :label="dict.nickName"
              >{{dict.nickName}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm2">确 定</el-button>
          <el-button @click="cancel2">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="单聊对话框" :visible.sync="singleOpen" width="900px"  height="800px" append-to-body>
        <single-chat
          :FROM="NICK_NAME"
          :TO="form2.onlineUser"
          :CHAT_ROOM_ID="CHAT_ROOM_ID"
        />
        <div slot="footer" class="dialog-footer">
           <el-button @click="cancel3">取 消</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>

  import CHAT from '@/utils/Chat'
  import SingleChat from "./singlechat";
  import { getOnlineUsers } from "@/api/login";

  import { Notification, MessageBox, Message, Loading } from 'element-ui'

  const appData = require("@/assets/face/emojis.json");


  export default {
   components: { SingleChat },
    data() {
      return {
        interval:null ,
        //表情框是否展示
        emojiShow: false,
        //表情列表
        faceList: [],
        // 弹出层标题
        title: "选择聊天方式",
        onlineTitle: "选择要聊天的小伙伴",
        // 是否显示弹出层
        open: false,
        onlineOpen: false,
        singleOpen: false,
        textarea: "",
        NICK_NAME: "",
        CHAT_ROOM_ID: "",
        imgUrl: Math.floor(Math.random() * 17) + 1 ,
        imgTaUrl: Math.ceil(Math.random() * 17) + 1 ,
        onlineUsers:[],
        onlineRadioUsers:[],
        messageList: [],
        // 表单参数
        form: {
          chatType : "10"
        },

        form2: {
          onlineUser : ''
        },
      };
    },
    watch: {

    },

    computed : {

      currentTime() {

        return CHAT.formatDate(new Date());

      },

      currentLocal() {
        let current = {
          latitude: "山东",
          longitude: "济南"
        };
        if (window.navigator.geolocation) {
          if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(
              (position) => {
                this.current = {
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude
                }
              },
              (error) => {
                console.log(error.message)
              },

              {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
              }
            );

          } else {

            console.log("Geolocation is not supported by your browser")
          }

          return current;
        }
      },

      computedTaImageSrc() {

        return require(`../assets/head/${this.imgTaUrl}.png`) ;

      },

      computedImageSrc() {

        return require(`../assets/head/${this.imgUrl}.png`) ;

      }

    },
    mounted() {
     this.loadEmojis() ;
      // 开始连接 webSocket 进行聊天
     let nickName =  this.$route.query.nickName  ;

     this.NICK_NAME = nickName ;

     let chatRoomId =  this.$route.query.chatRoomId  ;

     this.CHAT_ROOM_ID = chatRoomId ;

     CHAT.init(nickName,chatRoomId,this.messageList, this.$refs.chatWindow) ;
     let self = this ;
     // 初始化在线用户
      this.interval =  setInterval(function() {
        getOnlineUsers(chatRoomId).then( res => {
           self.onlineUsers = res.data  ;
          self.onlineRadioUsers = res.data ;
         })
      },2000)

      window.addEventListener("keydown", this.keyDowns);
    },
    methods: {
      //加载表情，存放到表情列表中
      loadEmojis() {
        for (let i in appData) {
          this.faceList.push(appData[i].char);
        }
      },
      // 获取用户点击之后的标签 ，存放到输入框内
      getEmojis(index) {
        for (let i in this.faceList) {
          if (index == i) {
            this.getBrowString = this.faceList[index];
            this.textarea += this.getBrowString;
          }
        }
        this.emojiShow = false;
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      cancel3() {
        this.singleOpen = false;
      },
      cancel2() {
        this.onlineOpen = false;
      },
      submitForm2(){
        // 单聊跳转
        // this.$router.push(
        //   {
        //     path : '/singlechat',
        //     query: {
        //       chatRoomId: this.CHAT_ROOM_ID, FROM: this.NICK_NAME,TO: this.form2.onlineUser
        //     }
        //   }
        // );
        if(this.form2.onlineUser === this.NICK_NAME){
          Message.error("单聊用户不能选择自己！")
          return ;
        }
        this.singleOpen = true ;
      },
      /** 提交按钮 */
      submitForm: function() {

       let ifSingleChat =  this.form.chatType
         if(ifSingleChat && ifSingleChat==='10'){
         this.onlineOpen = true ;
        }else {
          this.onlineOpen = false ;
          this.open = false ;
          // 群聊
          CHAT.sendMsg('ALL',this.messageList,this.textarea) ;
        }

      },

      /* 回车发送消息 */
      keyDowns(e) {
        if (e.key == "Enter") {
          this.send();
          e.preventDefault(); // 去掉默认的换行
        }
      },
      /* 点击发送消息 */
      send() {
        if( this.textarea  == ''){
          return ;
        }
        this.open = true ;
      },

      offLine(){

        if(this.interval != null ){
          clearInterval(this.interval)
        }
        if(CHAT.SOCKET){
          CHAT.SOCKET.close();
        }

      }
    },
    beforeDestroy() {
      if(this.interval != null ){
        clearInterval(this.interval)
      }
      window.addEventListener("keydown", this.keyDowns);
    },
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-textarea {
    height: calc(100% - 60px);
  }

  ::v-deep .el-textarea__inner {
    height: 105px !important;
    color: #fff;
    min-height: 105px !important;
    background-color: transparent;
    border: 0;
  }

  ::v-deep ::-webkit-scrollbar {
    background-color: transparent !important;
  }

  .message_left {
    border-top-right-radius: 5px;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
    background-color: #0c1324;
    margin-top: -5px;
  }
  .message_right {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
    background-color: #c05939;
    margin-top: 5px;
    margin-right: 20px;
  }

  .content {
    border: 2px solid #26c4d1;
    border-radius: 20px;
    background-color: rgba(49, 147, 192, 1);;
    box-shadow: 0 0 10px 1px #26c4d1;
    width: 50%;
    height: 800px;
    display: flex;
    margin: 10px auto auto auto ;

    .message_title {
      height: 50px;
      line-height: 50px;
      border-radius: 20px;
      color: #082b03;
      text-align: center;
      float: right;
      width: 50%;
      position: absolute;
      margin: auto auto auto auto ;
      background: transparent;
      ul {
        list-style: none;
         .ali {
          margin-top: -10px;
        }

        .bli {
          margin-left: -30px;
        }

        .cli {
          margin-left: 50%;
          line-height: 28px;
        }

      }

      ul li {
        float: left;
        font-weight: 800;
        font-style: normal;
        font-size: 14px;
        display: block; /* 将链接设为块级元素 */
        width: 75px; /* 设置宽度 */
        height: 30px; /* 设置高度 */
        line-height: 22px; /* 设置行高，将行高和高度设置同一个值，可以让单行文本垂直居中 */
        text-align: center; /* 居中对齐文字 */
        color: rgba(0, 0, 0, 0.647058823529412);
        text-decoration: none; /* 去掉下划线 */
      }

    }

    .message_input {
      // border: 1px solid #3e5a77;
      margin: 5px auto 0 auto;
      width: 42%;
      height: 50px;
      border-radius: 5px;
      box-shadow: 0 0 5px 1px #89d8f0;
      background-color: transparent ;
      position: absolute;
      margin: 39.5% auto auto auto ;
    }

    .message_face {
      // border: 1px solid #3e5a77;
      margin: 5px auto 0 auto;
      width: 42%;
      height: 50px;
      /*border-radius: 5px;*/
      /*box-shadow: 0 0 5px 1px #89d8f0;*/
      background-color: transparent ;
      position: absolute;
      margin: 37.5% auto auto auto ;
    }


    .room_content {
      width: 15%;
      height: 77%;
      border-radius: 5px;
      float: right;
      box-shadow: 0 0 5px 1px #89d8f0;
      background-color: rgba(96, 173, 207, 0.2);
      margin: 3% auto auto auto ;
      position: absolute;
      color: white;
      font-size: large;
      ul  {
        list-style: none;
      }

      ul li {
        list-style-type: none;
      }

      .romm_01 {
        color: white;
       }

      .romm_02 {
        color: white;
         margin-top: 20px;
      }
    }

    .message_content {
      width: 35%;
      height: 77%;
      border-radius: 5px;
      float: right;
      box-shadow: 0 0 5px 1px #89d8f0;
      background-color: rgba(255, 255, 255, 0.8);
      margin: 3% auto auto 15% ;
      position: absolute;
      .message_area {
        width: 100%;
        height: calc(100% - 3px);
        overflow-y: auto;

        .message_item {
          display: flex;
          justify-content: flex-end;
          margin: 5px 0;
          list-style-type: none;
          ul li {
            list-style-type: none;

          }

          .avator_left {
            width: 40px;
            height: 40px;
            margin-right: 10px;
            margin-left: -50px;
            cursor: pointer;
            border-radius: 10px;

            img {
              display: block;
              width: 100%;
              height: 100%;
             }
          }

          .avator_right {
            width: 40px;
            height: 40px;
            /*margin-right: 106px;*/
            /*margin-left: 10px;*/
            cursor: pointer;
            border-radius: 10px;

            img {
              display: block;
              width: 100%;
              height: 100%;
            }
          }

          .name_left {
            color: #67798e;
            height: 35px;
            width: 250px;
            margin-right: 150px;
            margin-top: -50px;
          }

          .name_right {
            color: #67798e;
            height: 40px;
            width: 50px;
            margin-left: 150px;
            margin-top: -30px;
          }

          .message {
            color: #ffffff;
            padding: 5px;
             border: 1px solid #71acbd;
          }
        }
      }


    }
  }


  ::v-deep .el-button {
    color: #082b03;
    border-radius: 5px;
    border: 1px solid #43a0a8;
    background-image: linear-gradient(to bottom, #15263b, #238298);
    margin-right: 10px;
  }

  .faceBox {
    width: 100%;
    height: 100px;
    background: #e6e6e6;
    position: absolute;
    z-index: 100;
    bottom: 0px;
    overflow: scroll;
    ul {
      display: flex;
      flex-wrap: wrap;
      padding: 5px;
      li {
        cursor: pointer;
        width: 5%;
        font-size: 16px;
        list-style: none;
        text-align: center;
      }
    }
  }

  .submit-btn {
    margin: 0 15px 10px 0;
    float: right;
  }



</style>
